package com.koron.css2.systemManage.servlet;

import com.koron.css2.ServerInterface;
import com.koron.css2.baseConfig.mapper.BusinessAreaMapper;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.css2.serviceManage.vo.BusinessAreaVo;
import com.koron.css2.systemManage.bean.OrgUserBean;
import com.koron.css2.systemManage.bean.OrgUserQueryBean;
import com.koron.css2.systemManage.bean.PostUserQueryBean;
import com.koron.css2.systemManage.dto.OrgUserPostDto;
import com.koron.css2.systemManage.mapper.OrgUserMapper;
import com.koron.css2.systemManage.mapper.PostUserMapper;
import com.koron.util.Constant;
import com.koron.util.Tools;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PostUserList implements ServerInterface {

    private static Logger log = LogManager.getLogger(PostUserSelect.class);

    /**
     * 执行岗位用户查询操作
     *
     * @param factory 会话工厂，用于获取数据库映射器
     * @param userInfo 用户信息，包含当前用户的水码等信息
     * @param req 请求Bean，包含查询所需的参数
     * @return 返回一个MessageBean对象，包含查询结果或错误信息
     */
    @Override
    public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
        // 创建一个成功消息Bean，用于返回查询结果
        MessageBean<List> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", List.class);
        try {
            // 将请求数据转换为PostUserQueryBean对象
            PostUserQueryBean bean = JsonUtils.objectToPojo(req.getData(), PostUserQueryBean.class);
            // 获取PostUserMapper映射器
            PostUserMapper mapper = factory.getMapper(PostUserMapper.class, "_default");
            // 获取OrgUserMapper映射器
            OrgUserMapper userMapper = factory.getMapper(OrgUserMapper.class);
            // 获取BusinessAreaMapper映射器
            BusinessAreaMapper businessAreaMapper = factory.getMapper(BusinessAreaMapper.class);
            // 检查岗位编号是否为空
            if(StringUtils.isBlank(bean.getPostNo())) {
                return MessageBean.create(Constant.MESSAGE_INT_FAIL, "请传入岗位。", null);
            }
            // 根据岗位编号查询用户账号列表
            List<String> list = mapper.selectUserByPost(bean);
            // 如果查询结果为空，返回空列表
            if(list == null || list.size() == 0) {
                info.setData(new ArrayList<>());
                return info;
            }
            // 创建用户查询Bean
            OrgUserQueryBean userQueryBean = new OrgUserQueryBean();
            userQueryBean.setUserAccounts(list);
            // 处理业务区域参数
            if (bean.getBusinessArea() != null){
               BusinessAreaVo businessAreaVo = businessAreaMapper.selectById(bean.getBusinessArea());
               if (businessAreaVo != null){
                   userQueryBean.setBusinessArea(businessAreaVo.getAreaNo());
               }
            }
            // 查询子区域编号列表
            List<String> areaIdList = Tools.queryChildrenAreaNo(bean.getBusinessArea(),userInfo.getCurWaterCode(),userQueryBean.getBusinessArea(),businessAreaMapper);
            userQueryBean.setBusinessAreaList(areaIdList);
            // 根据用户账号查询用户信息
            List<OrgUserBean> users = userMapper.selectByAccounts(userQueryBean);
            // 查询业务区域列表
            List<BusinessAreaVo> businessAreaBeans = businessAreaMapper.selectList(userInfo.getCurWaterCode());
            // 创建数据列表，用于存储查询结果
            List<OrgUserPostDto> data = new ArrayList<>();
            // 遍历业务区域，整理查询结果
            businessAreaBeans.forEach(businessAreaVo -> {
                List<Map<String,String>> res = new ArrayList<>();
                for(OrgUserBean t: users){
                    if (businessAreaVo.getAreaNo().equals(t.getBusinessArea())){
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("userAccount", t.getAccount());
                        map.put("userName", t.getUserName());
                        res.add(map);
                    }else {
                        if (res.size()>0){
                            OrgUserPostDto orgUserPostDto = new OrgUserPostDto();
                            orgUserPostDto.setUserInfos(res);
                            orgUserPostDto.setBusinessArea(businessAreaVo.getAreaNo());
                            orgUserPostDto.setBusinessAreaName(businessAreaVo.getAreaName());
                            data.add(orgUserPostDto);
                            res = new ArrayList<>();
                        }
                    }
                }
                if (res.size()>0){
                    OrgUserPostDto orgUserPostDto = new OrgUserPostDto();
                    orgUserPostDto.setUserInfos(res);
                    orgUserPostDto.setBusinessArea(businessAreaVo.getAreaNo());
                    orgUserPostDto.setBusinessAreaName(businessAreaVo.getAreaName());
                    data.add(orgUserPostDto);
                }
            });
            // 设置查询结果数据
            info.setData(data);
        } catch (Exception e) {
            // 异常处理，设置错误信息
            info.setCode(Constant.MESSAGE_INT_FAIL);
            info.setDescription(e.getMessage());
            log.error(e.getMessage(), e);
        }
        // 返回消息Bean
        return info;
    }


}

